﻿package net.wangit.view.unit.grid;

import java.util.ArrayList;
import java.util.List;

import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.util.Html;


public final class Tr {

	Group parent;
	private List tds;
	private int column;

	public Tr(Group parent) {
		tds = new ArrayList();
		column = 0;
		this.parent = parent;
	}

	public void write(ActionContext ac, StringBuffer html, Row row,
			int rowIndex, String rowCss) {
		html.append("<tr");
		Html.setId(html, parent.getRowId());
		Html.setAttribute(html, parent.getAttribute());
		Html.setCss(html, rowCss);
		Html.setVisible(html, parent.isVisible());
		html.append(">");
		for (int i = 0; i < tds.size(); i++) {
			Td td = (Td) tds.get(i);
			td.write(ac, html, rowIndex, row);
		}

		fill(html);
		html.append("</tr>");
	}

	public void writeListHead(ActionContext ac, StringBuffer html,
			String headCss) {
		html.append("<tr id=\"x\" class=\"").append(headCss).append("\">");
		for (int i = 0; i < tds.size(); i++) {
			Td td = (Td) tds.get(i);
			td.writeListHead(ac, html);
		}

		fill(html);
		html.append("</tr>");
	}

	public void addElement(ElementComponent element) {
		int colSpan = element.getTdColSpan();
		if (colSpan > 0 || tds.size() == 0) {
			tds.add(new Td(element));
			if (colSpan == 0)
				colSpan = 1;
			column += colSpan;
		} else {
			Td td = (Td) tds.get(tds.size() - 1);
			td.addElement(element);
		}
	}

	public void addColumn(ElementComponent element) {
		tds.add(0, new Td(element));
	}

	public void addColumn(int colSpan) {
		column += colSpan;
	}

	public boolean isFull() {
		return column >= parent.getColumn();
	}

	public boolean isEmpty() {
		return tds.size() == 0;
	}

	private void fill(StringBuffer html) {
		int count = parent.getColumn() - column;
		for (int i = 0; i < count; i++)
			html.append("<td></td>");

	}
}
